package com.sunwayhorizo.health.business.clinic.emr.template;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.base.BaseManager;
import com.sunwayhorizo.health.business.clinic.emr.template.query.MedicalImgQueryLocal;
import com.sunwayhorizo.health.business.dto.ResultsDTO;
import com.sunwayhorizo.health.business.dto.clinic.emr.template.MedicalImgDTO;
import com.sunwayhorizo.health.common.DataTypeUtil;
import com.sunwayhorizo.health.common.DateUtil;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.datatypes.CE;
import com.sunwayhorizo.health.hl7.datatypes.CS;
import com.sunwayhorizo.health.hl7.datatypes.ED;
import com.sunwayhorizo.health.hl7.datatypes.ST;
import com.sunwayhorizo.health.hl7.rim.ActParticipation;
import com.sunwayhorizo.health.hl7.rim.ControlAct;
import com.sunwayhorizo.health.hl7.rim.Document;
import com.sunwayhorizo.health.hl7.rim.Employee;
import com.sunwayhorizo.health.hl7.vocabulary.ActCode;
import com.sunwayhorizo.health.hl7.vocabulary.ActMood;
import com.sunwayhorizo.health.hl7.vocabulary.ParticipationType;

/**
 * @ClassName MedicalImgManager <br>
 * @PackageName com.sunwayhorizo.health.business.clinic.emr.template <br>
 * @Description 医学图片维护，不包含分类功能 <br>
 * @Author jinzw <br>
 * @Date 2011-1-3 <br>
 * @Version 1.0 <br>
 * @ModifiedDesc <br>
 * @ModifiedDate <br>
 * @ModifiedBy <br>
 * @Copyright 2010-2020 北京三维海容 All Rights Reserved. <br>
 */

@Name(value = "MedicalImgManager")
@Stateless
public class MedicalImgManager extends BaseManager implements MedicalImgManagerLocal
{

    private MedicalImgQueryLocal medicalImgQuery = (MedicalImgQueryLocal)Component.getInstance("MedicalImgQuery");
    
    public ResultsDTO newMedicalImg(MedicalImgDTO medicalImgDTO) throws Hl7Exception
    {
        if (null == medicalImgDTO)
        {
            log.info("新增医学图片失败，医学图片数据medicalImgDTO为null");
            return getResultsDTO("新增医学图片失败", false, null);
        }
        //创建图片库动作
        Document doc = creatmedicalImgDoc(); 
        //给图片库动作赋值
        converDocToMedicalImgDto(medicalImgDTO, doc);
        //得到维护图片库的员工角色
        Employee empRole = null;
        if(StrUtil.isNotEmpty(medicalImgDTO.getEmpRoleId()))
        {
            empRole = (Employee)baseQuery.findRoleById(Long.valueOf(medicalImgDTO.getEmpRoleId()));
        }
        //员工角色参与到图片库动作
        if(null != empRole)
        {
            ActParticipation part = getActFactory().newActParticipation();
            part.setTypeCode(ParticipationType.SBJ);
            addParticipation(empRole, part);
        }
        //ControlAct维护图片库关系
        ControlAct control = newControlAct(doc);
        em.persist(control);
        log.info("新增医学图片成功docId: " + doc.getActId());
        return getResultsDTO("新增医学图片成功", true, doc.getActId().toString());
    }


    @SuppressWarnings("rawtypes")
    public ResultsDTO delMedicalImg(List ids) throws Hl7Exception
    {
        if (ListUtil.isEmpty(ids))
        {
            log.info("删除医学图片列表失败，ids " + ids);
            return getResultsDTO("删除医学图片列表失败", false, null);
        }
        String id = (String) ids.get(0);
        Document doc = baseQuery.findDocumentById(id); 
        if (null == doc)
        {
            log.info("删除医学图片列表失败，未找到图片");
            return getResultsDTO("删除医学图片列表失败，未找到图片", false, null);
        }
        em.remove(doc);
        log.info("删除医学图片成功，id : " + id);
        return getResultsDTO("删除医学图片成功", true, id);
    }


    public ResultsDTO updateMedicalImg(MedicalImgDTO medicalImgDTO) throws Hl7Exception
    {
        if (null == medicalImgDTO)
        {
            log.info("更新医学图片列表失败，medicalImgDTO为空");
            return getResultsDTO("更新医学图片列表失败，medicalImgDTO为空", false, null);
        }
        //得到图片库动作
        Document doc = baseQuery.findDocumentById(medicalImgDTO.getId()); 
        if (null == doc)
        {
            log.info("更新医学图片列表失败，未找到图片");
            return getResultsDTO("更新医学图片列表失败，未找到图片", false, null);
        }
        //给图片库动作设置需要修改的值
        converDocToMedicalImgDto(medicalImgDTO, doc);
        em.merge(doc);
        log.info("更新医学图片列表成功"+doc.getActId());
        return getResultsDTO("更新医学图片列表成功", true, medicalImgDTO);
    }


    public ResultsDTO findMedicalImgList() throws Hl7Exception
    {
        List<Object> docs = medicalImgQuery.findMedicalImgList();

        if (ListUtil.isEmpty(docs))
        {
            log.info("获取医学图片列表失败");
            return getResultsDTO("获取医学图片列表失败", true, null);
        }
        //组装MedicalImgDTO 集合
        List<MedicalImgDTO> result = new ArrayList<MedicalImgDTO>();
        for (int i = 0; i < docs.size(); i++)
        {
            Object[] arg = (Object[]) docs.get(i);
            MedicalImgDTO mid = new MedicalImgDTO();
            if (null != arg[0])
            {
                mid.setId(arg[0].toString());
            }
            if (null != arg[1])
            {
                mid.setName(arg[1].toString());
            }
            result.add(mid);
        }

        log.info("获取医学图片内容成功，总记录数： " + result.size());
        return getResultsDTO("获取医学图片内容成功", true, result);
    }

    public ResultsDTO findMedicalImg(String id) throws Hl7Exception
    {
        if (StrUtil.isEmpty(id))
        {
            log.info("获取医学图片内容失败，id为空");
            return getResultsDTO("获取医学图片内容失败，id为空", false, null);
        }
        Document doc = baseQuery.findDocumentById(id);
        MedicalImgDTO result = convertDocToDto(doc);
        if (null == result)
        {
            log.info("获取医学图片内容失败，doc为空");
            return getResultsDTO("获取医学图片内容失败，doc为空", false, null);
        }

        log.info("获取医学图片内容成功，id" + id);
        return getResultsDTO("获取医学图片内容成功，id" + id, true, result);
    }


    private Document creatmedicalImgDoc() throws Hl7Exception
    {
        CS cs = ActMood.EVN;
        CE ce = getDataTypeFactory().newCE(ActCode.MEDICALIMG.code().stringValue()); 
        Document document = this.getActFactory().newDocument(cs, ce, null);
        return document;
    }


    private Document converDocToMedicalImgDto(MedicalImgDTO mid, Document document) throws Hl7Exception
    {
        if ((null == mid) || (null == document))
            return null;

        // 设置名称
        if (!StrUtil.isEmpty(mid.getName()))
        {
            ST name = getDataTypeFactory().newST(mid.getName());
            document.setTitle(name);
        }

        // 内容
        byte[] contents = mid.getContents();
        if (null != contents)
        { 
            // 如果内容不为空
            ED desc = DataTypeUtil.getED(" ", contents);
            document.setText(desc);
        }

        // 创建人
        if (!StrUtil.isEmpty(mid.getCreatedBy()))
        {
            document.setCreatedBy(Long.parseLong(mid.getCreatedBy()));
            document.setCreationDate(DateUtil.getTimestamp(DateUtil.GetDateTime()));
        }

        // 最后修改人
        if (!StrUtil.isEmpty(mid.getLastUpdateBy()))
        {
            document.setLastUpdatedBy(Long.parseLong(mid.getLastUpdateBy()));
            document.setLastUpdateDate(DateUtil.getTimestamp(DateUtil.GetDateTime()));
        }

        return document;
    }


    // 将Document转换为ClinicLibraryDTO
    private MedicalImgDTO convertDocToDto(Document doc) throws Hl7Exception
    {
        if (null == doc) return null;
        MedicalImgDTO mid = new MedicalImgDTO();
        // id
        mid.setId(doc.getActId().toString());
        // 名称
        ST name = doc.getTitle();
        mid.setName(name.stringValue());
        // 内容
        ED text = doc.getText();
        mid.setContents((text != null ? text.integrityCheck().byteArray() : null ));
        // 创建人
        mid.setCreatedBy(doc.getCreatedBy().toString());
        // 创建时间
        mid.setCreationDate(doc.getCreationDate());
        // 最后修改人
        mid.setLastUpdateBy(doc.getLastUpdatedBy().toString());
        // 最后修改时间
        mid.setLastUpdateDate(doc.getLastUpdateDate());
        return mid;
    }

}
